import 'package:flutter/material.dart';
import 'package:projectfluttershengyihuatong/category/catetory_controller.dart';
import 'package:projectfluttershengyihuatong/courseDetail/playerview.dart';
import 'package:projectfluttershengyihuatong/route.dart';
import 'package:projectfluttershengyihuatong/service/jsontool.dart';
import 'package:projectfluttershengyihuatong/service/launchservice/launchservice.dart';
import 'package:projectfluttershengyihuatong/service/request_manager.dart';
import 'package:projectfluttershengyihuatong/tab1/customview.dart';
import 'package:projectfluttershengyihuatong/tab2/questionInfo.dart';
import 'package:projectfluttershengyihuatong/tab2/questionlesson.dart';
import 'package:projectfluttershengyihuatong/tool/extension_int.dart';
import 'package:projectfluttershengyihuatong/tool/public_color.dart';
import 'package:projectfluttershengyihuatong/tool/tool.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'customview.dart';
import '../category/CatetoryModel.dart';
import '../service/loginService/logginservice.dart';
import 'package:get/get.dart';

class QuestionPage extends StatefulWidget {
  const QuestionPage({super.key});

  @override
  State<QuestionPage> createState() => _QuestionPageState();
}

class _QuestionPageState extends State<QuestionPage> {
  @override
  void initState() {
    // TODO: implement initState
    request().then((value) {
      setState(() {});
    });

    super.initState();
  }

  List<CatetoryModel> topDataArr = [];
  CatetoryModel? selectTopModel;

  Future<QuestionInfo?> requestInfo() async {
    if (selectTopModel == null) {
      return Future.value(null);
    }
    final pid = selectTopModel?.pid ?? 0;
    final url = LaunchService.getInstance().config?.api?.everyDayInfo ?? "";
    RequestManager.getInstance().dio.options.headers["token"] =
        LoginService.getInstance().userInfo?.token ?? "";
    final response = await RequestManager.getInstance()
        .dio
        .get(url, queryParameters: {"kemu_id": pid});
    final model = QuestionInfo.fromJson(response.data["data"]);
    return Future.value(model);
  }

  Future<List<ChapterAndLesson>?> requestLesson() async {
    if (selectTopModel == null) {
      return Future.value(null);
    }
    final pid = selectTopModel?.pid ?? 0;
    final url =
        LaunchService.getInstance().config?.api?.hailiangChapterLesson ?? "";
    RequestManager.getInstance().dio.options.headers["token"] =
        LoginService.getInstance().userInfo?.token ?? "";
    final response = await RequestManager.getInstance()
        .dio
        .get(url, queryParameters: {"kemu_id": pid});
    final model = Questionlesson.fromJson(response.data["data"]);
    return Future.value(model.chapterAndLesson);
  }

  QuestionInfo? info;
  List<ChapterAndLesson> lesson = [];

  Future<void> request({bool isRequestCategory = true}) async {
    if (isRequestCategory) {
      topDataArr = await requestCategory();
      selectTopModel = topDataArr.first;
    }
    info = await requestInfo();
    lesson = await requestLesson() ?? [];

    return Future.value();
  }

  @override
  Widget build(BuildContext context) {
    final tabs = topDataArr
        .map((e) => Tab(
              key: ValueKey(e.pid ?? 0),
              child: Text(e.title ?? ""),
            ))
        .toList();
    return DefaultTabController(
      length: topDataArr.length,
      child: Scaffold(
        appBar: PreferredSize(
          preferredSize: const Size.fromHeight(44),
          child: AppBar(
            backgroundColor: primaryColor,
            leading: CategoryBtn(
              voidCallback: () {},
            ),
            leadingWidth: 200.adapt(),
          ),
        ),
        body: Container(
          color: colorfa,
          child: Column(
            children: [
              TopTab(tabs: tabs, ontap: (index) async {
                selectTopModel = topDataArr[index];
                await request(isRequestCategory: false);
                setState(() {

                });
              },),
              Expanded(
                child: CustomScrollView(
                  slivers: [
                    QuestionCellClick(
                      callback: () {
                        Get.toNamed(RouteNames.PROBLEM, arguments: {"2":selectTopModel, "3":1});
                      },
                      info: info,
                    ),
                    const QuestionCell2(),
                    QuestionCell3(selectTopModel: selectTopModel, info: info),
                    const QuestionCell4(),
                    LessonWidget(lesson: lesson,catetoryModel: selectTopModel,),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }



  Future<List<CatetoryModel>> requestCategory() async {
    var shareManager = await SharedPreferences.getInstance();
    if (LoginService.getInstance().userInfo?.token != null) {
      RequestManager.getInstance().dio.options.headers["token"] =
          LoginService.getInstance().userInfo?.token ?? "";
    }
    final pid = CatetoryController.getInstance().leiModel?.pid?.toInt() ?? 0;
    final response = await RequestManager.getInstance().dio.get(
        "/api/project/getProjectByParentId",
        queryParameters: {"project_id": pid});
    final model = BaseModel<List<CatetoryModel>>.fromJson(response.data);
    return model.data ?? [];
  }
}

class LessonWidget extends StatefulWidget {
  LessonWidget({super.key, required this.lesson, required this.catetoryModel});
  List<ChapterAndLesson> lesson = [];
  final CatetoryModel? catetoryModel;

  @override
  State<LessonWidget> createState() => _LessonWidgetState();
}

class _LessonWidgetState extends State<LessonWidget> {
  @override
  Widget build(BuildContext context) {
    return SliverPadding(
      padding: const EdgeInsets.only(
          left: 8, right: 8, top: 10, bottom: 10),
      sliver: SliverToBoxAdapter(
        child: SingleChildScrollView(
          child: Container(
            child: CustomExpansionPanelList(
              // 组头和其子组件之间的距离
              expandedHeaderPadding: EdgeInsets.zero,
              // 阴影颜色
              elevation: 0,
              dividerColor: colorfa,
              materialGapSize: 10,


              children: widget.lesson.map((e) {
                return ExpansionPanel(
                    isExpanded: e.isSelected,
                    headerBuilder: (context, isexpand) {
                      if (isexpand) {
                        return lessoncell(
                          model: e,
                          isHiddenLeftBtn: false,
                          borderRadius: BorderRadius.only(
                              topLeft: Radius.circular(6),
                              topRight: Radius.circular(6)),
                          titleTextStyle: TextStyle(color: color33, fontSize: 16.adapt(), fontWeight: FontWeight.bold),
                          callback: (bo) {
                            e.isSelected = bo;
                            setState(() {});
                          },
                          toProblem: (){
                            Get.toNamed(RouteNames.PROBLEM, arguments: {"1": e, "2":widget.catetoryModel});
                          },
                        );
                      }else {
                        return lessoncell(
                          model: e,
                          isHiddenLeftBtn: false,
                          borderRadius: BorderRadius.circular(6),
                          titleTextStyle: TextStyle(color: color33, fontSize: 16.adapt(), fontWeight: FontWeight.bold),
                          callback: (bo) {
                            e.isSelected = bo;
                            setState(() {});
                          },
                          toProblem: (){
                            Get.toNamed(RouteNames.PROBLEM, arguments: {"1": e, "2":widget.catetoryModel});

                          },
                        );
                      }
                    },
                    body: ListView.separated(
                      itemBuilder: (context, index) {
                        final model = e.children?[index];
                        if ((index + 1) == (e.children?.length ?? 0)) {
                          return lessoncell(
                            model: model,
                            isHiddenLeftBtn: true,
                            borderRadius: BorderRadius.only(
                                bottomLeft: Radius.circular(6),
                                bottomRight: Radius.circular(6)),
                            titleTextStyle: TextStyle(color: color33, fontSize: 16.adapt(), fontWeight: FontWeight.normal),

                            callback: (bo) {},
                            toProblem: (){
                              Get.toNamed(RouteNames.PROBLEM, arguments: {"1": model, "2":widget.catetoryModel});
                            },
                          );
                        }else {
                          return lessoncell(
                            model: model,
                            isHiddenLeftBtn: true,
                            borderRadius: BorderRadius.zero,
                            titleTextStyle: TextStyle(color: color33, fontSize: 16.adapt(), fontWeight: FontWeight.normal),

                            callback: (bo) {

                            },
                            toProblem: (){
                              Get.toNamed(RouteNames.PROBLEM, arguments: {"1": model, "2":widget.catetoryModel});

                            },
                          );
                        }
                        
                      },
                      itemCount: e.children?.length ?? 0,
                      shrinkWrap: true,
                      physics: const NeverScrollableScrollPhysics(),
                      separatorBuilder: (BuildContext context, int index) {
                        return Divider(
                          height: 1,
                          thickness: 1,
                          color: colorfa,
                        );
                      },
                    ));
              }).toList(),
            ),
          ),
        ),
      ),
    );
  }
}

class lessoncell extends StatefulWidget {
  lessoncell({
    super.key,
    required this.model,
    required this.callback,
    required this.borderRadius,
    required this.isHiddenLeftBtn,
    required this.titleTextStyle,
    required this.toProblem
  });

  final ValueChanged<bool> callback;
  final ChapterAndLesson? model;
  BorderRadius borderRadius = BorderRadius.circular(6);
  final bool isHiddenLeftBtn;
  final TextStyle titleTextStyle;
  final VoidCallback toProblem;

  @override
  State<lessoncell> createState() => _lessoncellState();
}

class _lessoncellState extends State<lessoncell> {
  @override
  Widget build(BuildContext context) {
    return ClipRRect(
      borderRadius: widget.borderRadius,
      child: Container(
        color: Colors.white,
        height: 83.adapt(),
        child: Row(
          children: [
            Container(
              alignment: Alignment.topCenter,
              width: 50,
              height: double.infinity,
              child: widget.isHiddenLeftBtn ? Container(): IconButton(
                isSelected: widget.model?.isSelected ?? false,
                onPressed: () {
                  widget.model?.isSelected =
                      !(widget.model?.isSelected ?? false);
                  widget.callback(widget.model?.isSelected ?? false);
                  setState(() {

                  });
                },
                icon: Image.asset(
                  assetImage("icon-shouqi"),
                  width: 15,
                  height: 15,
                ),
                selectedIcon: Image.asset(
                  assetImage("icon-zhankai"),
                  width: 15,
                  height: 15,
                ),
              ),
            ),
            Expanded(
                child: Container(
              padding:
                  const EdgeInsets.only(left: 5, top: 10, bottom: 10, right: 0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    "${widget.model?.title ?? ""}",
                    style: widget.titleTextStyle,
                    maxLines: 1,
                  ),
                  Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Expanded(
                        child: RichText(
                            text: TextSpan(children: [
                          TextSpan(
                              text: "正确题数  ",
                              style: TextStyle(color: color66, fontSize: 14)),
                          TextSpan(
                              text: "${widget.model?.rightQuestionCount ?? 0}",
                              style:
                                  TextStyle(color: primaryColor, fontSize: 14)),
                          TextSpan(
                              text: "/${widget.model?.questionCount ?? 0}",
                              style: TextStyle(color: color66, fontSize: 14)),
                          const TextSpan(text: "   "),
                          TextSpan(
                              text: "正确率  ",
                              style: TextStyle(color: color66, fontSize: 14)),
                          TextSpan(
                              text: "${widget.model?.score ?? 0}%",
                              style:
                                  TextStyle(color: primaryColor, fontSize: 14)),
                        ])),
                      ),
                    ],
                  ),
                ],
              ),
            )),
            Container(
              width: 80,
              height: double.infinity,
              child: Center(
                child: IconButton(
                  constraints: BoxConstraints(
                    minWidth: 60.adapt(),
                    minHeight: 28.adapt(),
                    maxWidth: 60.adapt(),
                    maxHeight: 28.adapt(),
                  ),
                  padding: EdgeInsets.zero,
                  icon: Text(
                    "做题",
                    style: TextStyle(color: primaryColor, fontSize: 14.adapt()),
                  ),
                  style: ButtonStyle(
                    side: MaterialStatePropertyAll<BorderSide>(
                        BorderSide(color: primaryColor, width: 1)),
                  ),
                  onPressed: widget.toProblem,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class QuestionCell4 extends StatelessWidget {
  const QuestionCell4({
    super.key,
  });

  @override
  Widget build(BuildContext context) {
    return SliverPadding(
      padding: EdgeInsets.all(8),
      sliver: SliverToBoxAdapter(
        child: Container(
          height: 83.adapt(),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Expanded(
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(6),
                  child: Container(
                    color: Colors.white,
                    child: Column(
                      children: [
                        Image.asset(
                          assetImage("icon-cuotiji"),
                          width: 40,
                          height: 40,
                        ),
                        SizedBox(
                          height: 5,
                        ),
                        Text("错题集"),
                      ],
                    ),
                  ),
                ),
              ),
              Expanded(
                child: Column(
                  children: [
                    Image.asset(
                      assetImage("icon-zuotijilu"),
                      width: 40,
                      height: 40,
                    ),
                    SizedBox(
                      height: 5,
                    ),
                    Text("做题记录"),
                  ],
                ),
              ),
              Expanded(
                child: Column(
                  children: [
                    Image.asset(
                      assetImage("icon-shoucang"),
                      width: 40,
                      height: 40,
                    ),
                    SizedBox(
                      height: 5,
                    ),
                    Text("收藏试题"),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class QuestionCell3 extends StatelessWidget {
  const QuestionCell3({
    super.key,
    required this.selectTopModel,
    required this.info,
  });

  final CatetoryModel? selectTopModel;
  final QuestionInfo? info;

  @override
  Widget build(BuildContext context) {
    return SliverPadding(
      padding: EdgeInsets.only(left: 9, right: 9, top: 10),
      sliver: SliverToBoxAdapter(
        child: AspectRatio(
          aspectRatio: 16 / 9,
          child: ClipRRect(
            borderRadius: BorderRadius.circular(8),
            child: PlayerView(
              key: ValueKey(selectTopModel?.pid ?? 0),
              alivid: info?.questionVideoInfo?.alivid,
            ),
          ),
        ),
      ),
    );
  }
}

class QuestionCell2 extends StatelessWidget {
  const QuestionCell2({
    super.key,
  });

  @override
  Widget build(BuildContext context) {
    return SliverPadding(
      padding: const EdgeInsets.only(left: 9, right: 9, top: 10),
      sliver: SliverToBoxAdapter(
        child: AspectRatio(
          aspectRatio: 2.85,
          child: Container(
            child: Row(
              children: [
                Image.asset(assetImage("wratingleft")),
                const SizedBox(
                  width: 5,
                ),
                Expanded(
                  child: Column(
                    children: [
                      Image.asset(assetImage("wratingright1")),
                      const SizedBox(
                        height: 5,
                      ),
                      Image.asset(assetImage("wratingright2")),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

class QuestionCellClick extends StatelessWidget {
  const QuestionCellClick({
    super.key,
    required this.callback,
    this.info,
  });

  final VoidCallback callback;
  final QuestionInfo? info;

  @override
  Widget build(BuildContext context) {
    return SliverPadding(
      padding: const EdgeInsets.only(left: 9, right: 9),
      sliver: SliverToBoxAdapter(
        child: AspectRatio(
          aspectRatio: 2.9,
          child: Container(
            child: Stack(children: [
              Image.asset(
                assetImage("clockIn_back"),
                fit: BoxFit.fill,
              ),
              Positioned(
                  left: 10.adapt(),
                  top: 15.adapt(),
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      ClipOval(
                        child: Image.network(
                          LoginService.getInstance().userInfo?.head ?? "",
                          width: 38.adapt(),
                          height: 38.adapt(),
                        ),
                      ),
                      const SizedBox(
                        width: 10,
                      ),
                      Text(
                        "每日练习打卡营",
                        style: TextStyle(fontSize: 16.adapt(), color: color33),
                      )
                    ],
                  )),
              Positioned(
                right: 10,
                bottom: 22,
                width: 98.adapt(),
                height: 35.adapt(),
                child: OutlinedButton(
                  onPressed: callback,
                  style: ButtonStyle(
                    backgroundColor:
                        MaterialStatePropertyAll<Color>(primaryColor),
                    side: const MaterialStatePropertyAll<BorderSide>(
                        BorderSide.none),
                  ),
                  child: Text(
                    "去练习",
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 16.adapt(),
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
              ),
              Positioned(
                left: 10,
                bottom: 2,
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    CustomTopAndDownBtn(
                      callback: () {},
                      title: "${info?.days ?? 0}",
                      subTitle: "坚持(天)",
                    ),
                    const SizedBox(
                      width: 10,
                    ),
                    CustomTopAndDownBtn(
                      callback: () {},
                      title: "${info?.questionCount ?? 0}",
                      subTitle: "答题(道)",
                    ),
                    const SizedBox(
                      width: 10,
                    ),
                    CustomTopAndDownBtn(
                      callback: () {},
                      title: "${info?.accuracyRate ?? 0}",
                      subTitle: "准确率(%)",
                    ),
                  ],
                ),
              ),
              Positioned(
                child: Text(
                  "${info?.isClockIn == 1 ? "今日已打开" : "今日未打卡"}",
                  style: TextStyle(color: primaryColor),
                ),
                right: 5,
                top: 10,
              )
            ]),
          ),
        ),
      ),
    );
  }
}

class TopTab extends StatelessWidget {
  const TopTab({
    super.key,
    required this.tabs,
    required this.ontap,
  });

  final Function(int)? ontap;
  final List<Tab> tabs;

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: TabBar(
        onTap: ontap,
        indicator: UnderlineTabIndicator(
            borderRadius: BorderRadius.circular(1),
            borderSide: BorderSide(width: 2.0, color: primaryColor)),
        //消除了左侧的空白。
        tabAlignment: TabAlignment.start,
        isScrollable: true,
        // 底部线条
        // dividerColor: Colors.black,
        padding: EdgeInsets.zero,
        dividerHeight: 0,
        indicatorColor: primaryColor,
        labelStyle: TextStyle(
            color: primaryColor, fontSize: 16, fontWeight: FontWeight.bold),
        unselectedLabelStyle: TextStyle(
            color: color33, fontSize: 14, fontWeight: FontWeight.normal),
        indicatorWeight: 1,
        indicatorSize: TabBarIndicatorSize.label,
        indicatorPadding: const EdgeInsets.only(left: 10,right: 10),
        tabs: tabs,
      ),
    );
  }
}

class CustomTopAndDownBtn extends StatelessWidget {
  const CustomTopAndDownBtn({
    super.key,
    required this.callback,
    required this.title,
    required this.subTitle,
  });

  final VoidCallback callback;
  final String title;
  final String subTitle;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: callback,
      child: Container(
        padding: const EdgeInsets.all(10),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(
              title,
              style: TextStyle(color: primaryColor, fontSize: 14.adapt()),
            ),
            const SizedBox(
              height: 2,
            ),
            Text(
              subTitle,
              style: TextStyle(color: color99, fontSize: 13.adapt()),
            )
          ],
        ),
      ),
    );
  }
}

class CustomTabIndicator extends Decoration {
  /// Create an underline style selected tab indicator.
  ///
  /// The [borderSide] and [insets] arguments must not be null.
  const CustomTabIndicator({
    this.width = 20,
    this.strokeCap = StrokeCap.round,
    this.borderSide = const BorderSide(width: 2.0, color: Colors.white),
    this.insets = EdgeInsets.zero,
  })  : assert(borderSide != null),
        assert(insets != null);

  /// The color and weight of the horizontal line drawn below the selected tab.
  final BorderSide borderSide;

  /// Locates the selected tab's underline relative to the tab's boundary.
  ///
  /// The [TabBar.indicatorSize] property can be used to define the tab
  /// indicator's bounds in terms of its (centered) tab widget with
  /// [TabBarIndicatorSize.label], or the entire tab with
  /// [TabBarIndicatorSize.tab].
  final EdgeInsetsGeometry insets;

  ///新增的属性
  final double width; // 控制器宽度
  final StrokeCap strokeCap; // 控制器边角形状

  @override
  Decoration? lerpFrom(Decoration? a, double t) {
    if (a is CustomTabIndicator) {
      return CustomTabIndicator(
        borderSide: BorderSide.lerp(a.borderSide, borderSide, t),
        insets: EdgeInsetsGeometry.lerp(a.insets, insets, t)!,
      );
    }
    return super.lerpFrom(a, t);
  }

  @override
  Decoration? lerpTo(Decoration? b, double t) {
    if (b is CustomTabIndicator) {
      return CustomTabIndicator(
        borderSide: BorderSide.lerp(borderSide, b.borderSide, t),
        insets: EdgeInsetsGeometry.lerp(insets, b.insets, t)!,
      );
    }
    return super.lerpTo(b, t);
  }

  @override
  BoxPainter createBoxPainter([VoidCallback? onChanged]) {
    return _UnderlinePainter(this, onChanged);
  }

  ///决定控制器宽度的方法
  Rect _indicatorRectFor(Rect rect, TextDirection textDirection) {
    assert(rect != null);
    assert(textDirection != null);
    final Rect indicator = insets.resolve(textDirection).deflateRect(rect);

    // 希望的宽度
    double wantWidth = this.width;
    // 取中间坐标
    double cw = (indicator.left + indicator.right) / 2;

    print(
        '$cw,indicator left${indicator.left}, right ${indicator.right}, indicator top ${indicator.top},indicator bottom${indicator.bottom}, border width${borderSide.width}');
    //这里是核心代码 //下划线靠左
    // return Rect.fromLTWH(indicator.left,
    //     indicator.bottom - borderSide.width, wantWidth, borderSide.width);

    //下划线居中
    return Rect.fromLTWH(cw - wantWidth / 2,
        indicator.bottom - borderSide.width, wantWidth, borderSide.width);
  }

  @override
  Path getClipPath(Rect rect, TextDirection textDirection) {
    return Path()..addRect(_indicatorRectFor(rect, textDirection));
  }
}

class _UnderlinePainter extends BoxPainter {
  _UnderlinePainter(this.decoration, VoidCallback? onChanged)
      : assert(decoration != null),
        super(onChanged);

  final CustomTabIndicator decoration;

  ///决定控制器边角形状的方法
  @override
  void paint(Canvas canvas, Offset offset, ImageConfiguration configuration) {
    assert(configuration != null);
    assert(configuration.size != null);
    final Rect rect = offset & configuration.size!;
    final TextDirection textDirection = configuration.textDirection!;
    final Rect indicator = decoration
        ._indicatorRectFor(rect, textDirection)
        .deflate(decoration.borderSide.width / 2.0);
    final Paint paint = decoration.borderSide.toPaint()
      ..strokeCap = decoration.strokeCap; //这块更改为想要的形状
    canvas.drawLine(indicator.bottomLeft, indicator.bottomRight, paint);
  }
}
